/**
 * Created by seikann on 2017-10-12.
 */
const models = require('../mongoDB/db');
const express = require('express');
const router = express.Router();

router.post('/api/login/loginApi', (req, res) => {
  models.Login.findOne({userName: req.body.userName}, (err, data) => {
    if (err) {
      res.send(err);
    } else if (!data) {
      req.session.error = '用户名不存在';
      res.send({
        message: '用户名不存在',
        code: '-1'
      });
    } else {
      if (req.body.password != data.password) {
        req.session.error = "密码错误";
        res.send({
          message: '密码错误',
          code: '-1'
        });
      } else {
        req.session.user = data;
        res.send({
          message: '登录成功',
          code: '0'
        });
      }
    }
  });
  // 通过模型去查找数据库
});
router.post('/api/login/register', (req, res) => {
  let newAccount = new models.Login({
    userName: req.body.userName,
    password: req.body.password
  });
  // 保存数据newAccount数据进mongoDB
  let criteria = {userName: req.body.userName};
  models.Login.find(criteria, (err, data) => {
    if (err) {
      res.send(err);
    } else {
      if (data.length == 0 && req.body.userName != "") {
        newAccount.save((err, data) => {
          if (err) {
            res.send(err);
          } else {
            res.send({
              message: "注册成功",
              code: "0"
            });
          }
        });
      } else {
        res.send({
          message: "账号已存在或账号密码不能为空",
          code: "-1"
        });
      }
    }
  });
  // 通过模型去查找数据库
});

module.exports = router;
